package com.javaee.service.user.impl;



import org.springframework.ai.client.AiClient;
import org.springframework.ai.prompt.Prompt;
import org.springframework.ai.prompt.messages.AssistantMessage;
import org.springframework.ai.prompt.messages.Message;
import org.springframework.ai.prompt.messages.UserMessage;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class Completion {
    private final AiClient aiClient;
    private final static Integer MAX_SIZE = 10;
    private String completion;
    private List<Message> messages = new ArrayList<>();

    public Completion(AiClient aiClient) {
        this.aiClient = aiClient;
    }

    private Completion addUserMessage(String message){
        Message userMessage = new UserMessage(message);
        messages.add(userMessage);
        return this;
    }

    private Completion addAssistantMessage(String message){
        Message assistantMessage = new AssistantMessage(message);
        messages.add(assistantMessage);
        return this;
    }

    public String chat(String message){
        addUserMessage(message);
        String result = aiClient.generate(new Prompt(messages)).getGeneration().getText();
        addAssistantMessage(result);
        update();
        return result;
    }

    private void update(){
        if(messages.size() > MAX_SIZE){
            messages = messages.subList(messages.size() - MAX_SIZE, messages.size());
        }
    }
}
